/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.web.instruction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.impl.util.SpringUtils;
import net.paoding.rose.web.impl.view.RoseViewResolver;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

/**
 * 
 * @author qieqie.wang@paoding.net
 * 
 */
public class ViewInstruction extends AbstractInstruction {

	private static Log logger = LogFactory.getLog(ViewInstruction.class);

	// 视图名称
	private String name;

	// 非空时，设置该页面的内容格式
	private String contentType;

	// 非空时，设置该页面的编码格式
	private String encoding;

	// render时使用它
	private ViewResolver roseViewResolver;

	@Override
	public void render(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (contentType() != null) {
			response.setContentType(contentType());
		}
		if (encoding() != null) {
			response.setCharacterEncoding(encoding());
		}
		View view = getRoseViewResolver().resolveViewName(name,
				request.getLocale());
		view.render(getModel().getAttributes(), request, response);
	}

	protected ViewResolver getRoseViewResolver() {
		if (roseViewResolver != null) {
			return roseViewResolver;
		}
		// XXX: Spring 2.5的@Autowired有bug:
		// 第一次因为没有bean无法Autowire，这很正常。问题是： 即使后面已经register了该bean的定义后，
		// 也还不能再Autowire。这些代码就是为了解决这个bug，此时需要自己手工getBean处理获取。
		roseViewResolver = (ViewResolver) SpringUtils.getBean(
				getApplicationContext(), "roseViewResolver");
		if (roseViewResolver == null) {
			roseViewResolver = registerRoseViewResolver();
		}
		return roseViewResolver;
	}

	public ViewInstruction contentType(String contentType) {
		setContentType(contentType);
		return this;
	}

	public ViewInstruction encoding(String encoding) {
		setEncoding(encoding);
		return this;
	}

	public ViewInstruction name(String name) {
		setName(name);
		return this;
	}

	public void setName(String name) {
		this.name = resolvePlaceHolder(name);
	}

	public void setEncoding(String encoding) {
		this.encoding = resolvePlaceHolder(encoding);
	}

	public void setContentType(String contentType) {
		this.contentType = resolvePlaceHolder(contentType);
	}

	public String encoding() {
		return encoding;
	}

	public String contentType() {
		return contentType;
	}

	/**
	 * 注册一个 {@link RoseViewResolver}定义到上下文中，以被这个类的所有实例使用
	 * 
	 * @return
	 */
	protected RoseViewResolver registerRoseViewResolver() {
		// 并发下，重复注册虽然不会错误，但没有必要重复注册
		synchronized (getApplicationContext()) {
			String beanName = "roseViewResolver";
			if (SpringUtils.getBean(getApplicationContext(), beanName) == null) {
				GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
				beanDefinition.setBeanClass(RoseViewResolver.class);
				((BeanDefinitionRegistry) getApplicationContext()
						.getBeanFactory()).registerBeanDefinition(beanName,
						beanDefinition);
				logger.info("registered bean definition:"
						+ RoseViewResolver.class.getName());
			}
			return (RoseViewResolver) SpringUtils.getBean(
					getApplicationContext(), beanName);
		}
	}
}
